﻿var ffSurvey = {};
ffSurvey.questionarray = new Array();
ffSurvey.visibilitydictionary = new Array();

ffSurvey.addVisibilityRule = function(qid, cid) {
	ffSurvey.questionarray[ffSurvey.questionarray.length] = qid;
	ffSurvey.visibilitydictionary[qid] = cid;
};

ffSurvey.enforceVisibility = function() {
    for (var qid in ffSurvey.questionarray) {
        var component = $(document.getElementById("ffComponent_" + ffSurvey.questionarray[qid]));

        if ($(".componentedit", component).length > 0) {
            component.addClass("ff-hiddenfield-edit");
        } else {
            component.addClass("ff-hiddenfield");
        }

        $(".ff-questionChoice").each(function() {
            for (var cid in ffSurvey.visibilitydictionary[ffSurvey.questionarray[qid]]) {
                if (ffSurvey.visibilitydictionary[ffSurvey.questionarray[qid]][cid] == $(this).attr("data-ff-choiceid") && this.checked && $(this).closest('.ff-hiddenfield').length == 0) {
                    $(document.getElementById("ffComponent_" + ffSurvey.questionarray[qid])).removeClass("ff-hiddenfield").removeClass("ff-hiddenfield-edit");
                }
            }
        });

        $(".ff-questionSelect").each(function() {
            for (var cid in ffSurvey.visibilitydictionary[ffSurvey.questionarray[qid]]) {
                if (ffSurvey.visibilitydictionary[ffSurvey.questionarray[qid]][cid] == $(this).val() && $(this).closest('.ff-hiddenfield').length == 0) {
                    $(document.getElementById("ffComponent_" + ffSurvey.questionarray[qid])).removeClass("ff-hiddenfield").removeClass("ff-hiddenfield-edit");
                }
            }
        });
    }
};

ffSurvey.ffFormValidate = function(form) {
    var fail = false;
    $('.questiontable', form).removeClass('questionanswerinvalid');
    // skip last element of ffRequiredFields, it'll be "-1" to make the xsl logic easier
    for (var i = 0; i < ffRequiredFields.length - 1; i++) {
        var obj = form["q" + ffRequiredFields[i]];
        if (!obj) {
            // might be multi selects
            obj = $('input[name^=q' + ffRequiredFields[i] + ':]', form);
            if (obj.length == 0)
                continue;
        }
        if ($(obj).closest('.ff-hiddenfield').length > 0) continue;
        if ($(obj).closest('.ff-hiddenfield-edit').length > 0) continue;
        if ($(obj).is('.ff-validation-ignore')) continue;
        if (obj.type == "text" || obj.type == "textarea" || obj.type == "file") { // check for text fields
            if (obj.value == "") {
                fail = true;
                $(obj).closest('.questiontable').addClass('questionanswerinvalid');
            }
        }
        else if (obj.type == "select-one") { // check for drop downs
            if ($(obj).val() == "") {
                fail = true;
                $(obj).closest('.questiontable').addClass('questionanswerinvalid');
            }
        }
        else if (obj.length) { // check for radio buttons, the object will actually be an array
            var radio_fail = true;
            for (var j = 0; j < obj.length; j++) {
                if (obj[j].checked)
                    radio_fail = false;
            }
            if (radio_fail) {
                fail = true;
                $(obj).closest('.questiontable').addClass('questionanswerinvalid');
            }
        }
    }
    try {
        if (ffSurvey.ffEmailField !== undefined) {
            var emailPattern = /^([a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})?$/;
            if (!emailPattern.test(form["q" + this.ffEmailField].value) || ((form["q" + this.ffEmailField].value == '') && (form["copyself"].checked))) {
                fail = true;
                $(form["q" + this.ffEmailField]).closest(".questiontable").addClass('questionanswerinvalid');
            }
        }
    } catch (e) { }
    // also check fields that have a custom regex requirement
    $('*[data-ff-form-regex]').each(function() {
        // this does not check for empty fields, we've already done that
        if ($(this).val() == '') return;
        var re = new RegExp($(this).attr('data-ff-form-regex'), 'i');
        var m = re.exec($(this).val());
        if (m == null) {
            fail = true;
            $(this).closest(".questiontable").addClass('questionanswerinvalid');
        }
    });
    if (fail)
        alert("Please fill in all required fields and ensure that your responses are valid.  Problematic responses have been highlighted.");
    else {
        // disable the submit button to prevent double submission
        $('.ff-form-submit', form).each(function() {
            this.disabled = true;
        });
    }
    return !fail;
}

var ffTest = {};
ffTest.ffQuestionList = []; // associative array: [question name: input type, question name: input type, ...]
ffTest.ffTestSubmit = false;
ffTest.ffFormSubmit = function(form) {

    if (!ffTest.ffFormBlankValidate(true)) return false;

    ffTest.ffTestSubmit = true;

    // disable the submit button to prevent double submission
    $('.ff-form-submit', form).each(function() {
        this.disabled = true;
    });

    return true;
}

ffTest.ffFormBlankValidate = function(submit) {

    // Count the blank answers
    var blankQs = [];
    for (var a in ffTest.ffQuestionList) {

        var val;
        if (ffTest.ffQuestionList[a] == 'radio') {
            val = $('form[name=testform] input:radio[name=' + a + ']:checked').val();
        } else if (ffTest.ffQuestionList[a] == 'checkbox') {
            val = 'checkbox ares never blank';
        } else {
            val = $('form[name=testform] [name=' + a + ']').val();
        }

        if (!val || val == "")
            blankQs.push(a);
    }

    // Do we need to validate?
    if (blankQs.length > 0) {

        // Display the confirmation box if required
        $confBox = $('.ff-form-blankconfirm');
        $confBox.find('label').text('Confirm submission with ' + blankQs.length + ' answer' + (blankQs.length == 1 ? '' : 's') + ' blank');

        if ($confBox.is(':visible')) {
            if ($confBox.find('input').is(':checked'))
                return true;
        } else {
            if (!submit) return false;
            $('.ff-form-blankconfirm').show();
        }

        $confBox.find('input').attr('checked', false);

    } else {
        $('form[name = testform] .questiontable.questionanswerinvalid').removeClass('questionanswerinvalid');
        $('.ff-form-blankconfirm').hide();
        return true;
    }

    // Highlight all the blank questions (only if the form is not going to be submitted)
    $('form[name = testform] .questiontable.questionanswerinvalid').removeClass('questionanswerinvalid');
    for (var a in blankQs) {
        $('form[name=testform] [name=' + blankQs[a] + ']:first').closest('.questiontable').addClass('questionanswerinvalid');
    }

    // Show an alert
    if (submit) {
        var alertText = "Submission Prevented\n\n";
        alertText += "Some of your answers were blank.  Please note that your submission is final.\n\n";
        alertText += "If you are sure you would like to submit with some answers blank, please tick the confirmation box.";
        alert(alertText);
    }

    return false;
}

$(function() {
    if ($('.ff-form-datepicker').datepicker({ dateFormat: 'dd/mm/yy' }).length > 0) {
        checkStyles(ffBaseURL + 'Templates/lib/jquery/css/ui-lightness/jquery-ui-1.8.2.custom.css');
    }

    if ($('.ff-email-submit-file').attr('disabled')) {
        $('.ff-email-submit-also, .ff-form-submit, .ff-email-submit-file').hide();
        $('.ff-email-submit p:first').css('margin-top', '0');
    }
    
    // trap enter in text box and convert to tab
    $('form[name=testform] input[type=text]').keydown(function(e) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        if (key == 13) {
            e.preventDefault();
            var inputs = $(this).closest('form').find(':input:visible');
            inputs.eq(inputs.index(this) + 1).focus();
        }
    });
});
